# -*- coding: utf-8 -*-
import socket
import time
import socket
import random


class NeiborTools:
    def __init__(self, broadcast, port, min_wait, max_wait, lost_time):
        self.neibers = {}
        self.bs = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        self.bs.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
        self.bs.setblocking(False)  # 设置成非阻塞
        self.port = port
        self.broadcast = broadcast
        self.bs.bind(('0.0.0.0', port))
        self.min_wait = min_wait
        self.max_wait = max_wait
        self.lost_time = lost_time

    def msg_broadcast(self):
        '''
        向邻居广播hello包
        '''
        while True:
            time.sleep(random.uniform(self.min_wait, self.max_wait))
            msg = str(time.time()).encode('utf-8')
            self.bs.sendto(msg, (self.broadcast, self.port))

    def neiber_update(self):
        '''
        邻居更新
        :return:
        '''
        while True:
            for n in self.neibers:
                if self.neibers[n] > 0:
                    self.neibers[n] -= 1
            while True:
                try:
                    data, addr = self.bs.recvfrom(1024)
                    ip = addr[0]
                    self.neibers[ip] = self.lost_time
                except:
                    break
            connect_neibers = []
            lost_neibers = []
            for k, v in self.neibers.items():
                if v > 0:
                    connect_neibers.append(k)
                else:
                    lost_neibers.append(k)
            for k in lost_neibers:
                self.neibers.pop(k)
            yield connect_neibers, lost_neibers
